<?php

namespace Modules\Asset\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Asset\Entities\WithdrawRecord;

use Validator;
use ThrowException;
use Auth;

class WithdrawRecordController extends Controller
{
    public function statusTotal(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();
        
        $total = [
            'pending' => WithdrawRecord::status('pending')->count(),
            'completed' => WithdrawRecord::status('completed')->count(),
            'closed' => WithdrawRecord::status('closed')->count(),
            // 'marked' => $class::status('marked')->count(),
        ];

        return [
            'total' => $total
        ];
    }

    public function index(Request $req, $assetType)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // $user = Auth::requireLoginUser();

        in_array($assetType, array_keys(config('asset.map'))) || ThrowException::Conflict('错误的资产类型');

        $options = $req->all();

        $options['scopes']['type'] = $assetType;
        $options['with'] = ['user'];

        $list = WithdrawRecord::getList($options);

        return $list->generateListResponse();
    }

    public function update(Request $req, $assetType, $uuid)
    {
        $rule = [
            'type' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // $user = Auth::requireLoginUser();

        // \Log::error($assetType);

        in_array($assetType, array_keys(config('asset.map'))) || ThrowException::Conflict('错误的资产类型');

        $options = $req->all();

        $item = WithdrawRecord::getEntity([
            'asset_type' => $assetType,
            'uuid' => $uuid
        ]);

        if ($req->type == 'complete') {
            $item->complete([
                'remark' => $req->input('remark')
            ]);
        }
        else if ($req->type == 'close') {
            $item->close();
        }
        else if ($req->type === 'start_auto_pay') {
            $item->startAutoPay();
        }

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = WithdrawRecord::getEntity([
            'uuid' => $uuid
        ]);

        if ($item->union_status === 'pending') {
            ThrowException::Conflict('待处理的提现不允许删除');
        }

        $item->delete();

        return [];
    }
}
